<?php

class fkeyAction extends Object implements actionInterface{
    
    private $form = NULL;
    private $name      = "";
    private $value     = "";
    private $arr       = "";
    private $data      = "";
    private $formmodel = "";
    public function __construct() {
        $this->LoadResource('html', 'html');
        $this->LoadResource('jqueryui/dialogs','cbox');
    }
    
    public function validar($name, $value, &$array){
        //$model = $value['model'];
        //$this->LoadModel($model, "model_obj");
        $type = $value['cardinalidade'];
        if($type == "1n"){
            if(is_array($array))
                $array = array_shift($array);
            elseif($array == "")
                $array = "FUNC_NULL";
        }
        elseif($type == "nn"){
            if($array == "") 
                return true;
            if(!is_array($array)){
                $array = explode(",", $array);
                if(count($array) == 1){
                    $array = array_shift($array);
                }
                
            }
            if(empty ($array))
                $array = "";
        }
        elseif($type == "n1"){
            if(!array_key_exists("fkn1", $_SESSION)) return true;
            if(!array_key_exists($value['model'], $_SESSION['fkn1'])) return true;
            $out = array();
            foreach($_SESSION['fkn1'][$value['model']] as $arr){
                $out[] = unserialize($arr);
            }
            $array = $out;
        }
        return true;
    }
    
    public function executar($name, $value, $array, $form){
        
        $ignore = array('hide', 'hidden', 'autentication', 'session');
        if(array_key_exists("especial", $array)){
            if(in_array($array['especial'], $ignore)) return true;
        }

        $this->form      = $form;
        $this->name      = $name;
        $this->value     = $value;
        $this->arr       = $array;
        $this->data      = $this->form->getVar($name);
        $this->formmodel = $this->form->getModel();
        
        $type = "cardinalidade_" . $value['cardinalidade'];
        if(!method_exists($this, $type)){
            return true;
        }
        
        $this->model = $value['model'];
        $this->LoadModel($this->model, "model_obj");
        $this->$type();
    }
    
    private function cardinalidade_11(){
        $this->LoadResource("formulario", "fgen");
        $this->LoadModel($this->model, "model_11");
        $dados = $this->model_11->getDados();
        foreach($dados as $name => $dado)$out[$name] = $dado;
        $this->fgen->genForm($out, $this->data);
    }
    
    private function cardinalidade_1n(){
        if(!isset($this->cbox)){
            $this->LoadResource('jqueryui/dialogs','cbox');
            $this->cbox->ajaxDialog('.addnew');
        }
        $name     = $this->arr['name'];     
        $names    = str_replace(array("[", "]"), "", $this->name);
        $keys     = $this->value['keys'];
        $desc     = (array_key_exists('description', $this->arr))?$this->arr['description']:"";
        $selected = (array_key_exists('default', $this->arr))  ?$this->arr['default']  :"";
        
        $this->comp = new Component();
        //$name  .= " ".$this->comp->getFkeyLink("$this->model", $this->value);
        $filtro   = "";
        if(array_key_exists('filther', $this->arr)){
            $fk1n = new FK1nModel();
            $filtro = $fk1n->filther($this->arr['filther']);
        }
        
        $count = $this->model_obj->getCount($filtro);
        if((array_key_exists('select_type', $this->arr) && ($this->arr['select_type'] == 'simple')) && $count > 0 || $count < 20){
            $k1 = array_shift($keys);
            $k2 = array_shift($keys);
            $order = array_key_exists('select_order', $this->arr)?$this->arr['select_order']:"$k2 ASC";
            $dados = $this->model_obj->selecionar(array($k1, $k2), $filtro, '','', $order);
                    
            //echo $this->model_obj->db->getSentenca(); print_r($dados);
            $out = array();
            if(!empty($dados)){
                foreach($dados as $arr){
                    $out[$arr[$k1]] = $arr[$k2];
                }
            }
            if(!array_key_exists('notnull', $this->arr) || $this->arr['notnull'] == false){
                    $selected = ($selected != "")?$selected:0;
            }
            $this->form->select($names, $out, $selected, $name, $desc);
        }
        else{
            $this->LoadJsPlugin("formulario/jqtokeninput", "ac");
            $value = "";
            if(is_array($this->data) && !empty ($this->data)){
                $k1 = array_keys($this->data);
                $k2 = array_values($this->data);

                $k1 = array_shift($k1);
                $k2 = array_shift($k2);
                $value = $k1;
                $this->ac->addItem($k1, $k2);
            }elseif($selected != "" && !is_array($selected)){
                $ks = $keys;
                $k1 = array_shift($ks);
                $k2 = array_shift($ks);
                $it = $this->model_obj->selecionar(array($k1, $k2), "$k1 = '$selected'");
                if(!empty($it)){
                    $it = array_shift($it);
                    $this->ac->addItem($it[$k1], $it[$k2]);
                }
            }
            
            $this->ac->setForm($this->form);
            $this->ac->setQuery($filtro);
            $this->ac->autocomplete($names, $this->model, $keys, $max = 10, $madd = 1, $this->value['model']);
            $this->form->text($names, $name, $value, $desc);
        }
    }
    
    private function cardinalidade_n1(){

        $ajaxid = 'n1_'.str_replace("/", "_", $this->model);
        $link = $this->html->getActionLinkIfHasPermission($this->model . '/formulario', "Add", '', $ajaxid);
        ob_start();
        $this->LoadComponent($this->model, 'md');
        $this->md->listInTable($this->model, $this->data, $this->arr['name'] .' '.$link);
        $var = ob_get_contents();
        ob_end_clean();
        
        $dados = $this->model_obj->getDados();
        $this->LoadResource('formulario', 'form_h');
        $form_h = new formularioResource();
        $form_h->printable();
        $var .= $form_h->NewForm($dados);
        
        $this->LoadJsPlugin('formulario/jqueryvalidate', 'jsval');
        $this->jsval->addToReset('alert("oi");');
        $formid = $form_h->getForm()->getFormName($dados);
        $this->form_h->getForm()->append("<div class='formn1'>$var</div>");
        $this->html->LoadJqueryFunction("
            //$('form#$formid').hide();
            $('#$ajaxid').click(function(){
                if($(this).hasClass('esconder')){
                    $(this).html('Add').removeClass('esconder');
                    $('form#$formid').slideUp('fast');
                }else{
                    $(this).html('Hide').addClass('esconder');
                    $('form#$formid').slideDown('fast');
                }
                return false;
            });
            $('form#$formid #enviar').click(function(){
                //alert('clicou');
                //return false;
            });

        ");
    }
   
    private function cardinalidade_nn(){
        
        $name      = $this->arr['name'];
        $formmodel = isset($this->arr['fkey']['formmodel'])?$this->arr['fkey']['formmodel'] :$this->formmodel;
        $data      = $this->model_obj->getDados();       
        $pkeys     = $this->model_obj->getPkey();
        $sname     = $tname = "";
        foreach($pkeys as $pk){
            $dado    = $data[$pk];
            $temp_md = $dado['fkey']['model'];
            if($temp_md == $formmodel){
                $formmodel = "";
                $tname     = $pk;
            }else{
                
                $sname = $pk;
                $this->comp = new Component();
                $name  = $this->arr['name'] . " " . $this->comp->getFkeyLink($temp_md, $dado['fkey']);
            }
        }

        $desc     = (array_key_exists('description', $this->arr))?$this->arr['description']:"";
        $names = str_replace(array("[", "]"), "", $this->name);
        if(!array_key_exists($tname, $data) ||
           !is_array($data[$tname]['fkey']) ||
           !array_key_exists('keys', $data[$tname]['fkey'])) {
           if(DEBUG) {
               echo "<h1>Warning: FkeyAction - Não foi possível encontrar a referência para o formulário,
                favor verificar se no modelo a variável [fkey][formmodel] foi configurada corretamente</h1>";
           }
           $this->form->text($names,$name, '', $desc);
           return;
        }

        $tmp_value = array_shift($data[$tname]['fkey']['keys']);
        $tmp_value = $this->form->getVar($tmp_value);
        $keys    = $data[$sname]['fkey']['keys'];
        $model   = $data[$sname]['fkey']['model'];
        $this->LoadJsPlugin("formulario/jqtokeninput", "ac");
        
        $key = $keys;
        $k1 = array_shift($key);
        $k2 = array_shift($key);
        $values = array();
        
        $selected = array();
        if(is_array($this->data)) $selected = $this->data;
        else                      $selected = (array_key_exists('default', $this->arr))  ?$this->arr['default']  :array();
        
        foreach($selected as $value){
            $values[] = $value[$k1];
            $this->ac->addItem($value[$k1], $value[$k2]);
        }
        
        $filtro =  (array_key_exists('filther', $this->arr['fkey']))? $this->arr['fkey']['filther']:"";
        $this->ac->setQuery($filtro);
        
        $values = implode(",", $values);
        $this->ac->setForm($this->form);
        $this->ac->autocomplete($names, $model, $keys, 10, "", $this->model);
        $this->form->text($names,$name, $values, $desc);
    }
   
}

?>